class User < ActiveRecord::Base
  set_table_name "users"
  set_primary_key "user_id"

  has_many :projects,
           :class_name  => 'UserProject' ,
	   :foreign_key => 'user_fk';

  has_many :task_comments,
           :class_name  => 'CommentTask',
	   :foreign_key => 'user_fk';
  
  has_many :project_comments,
           :class_name  => 'CommentProject',
           :foreign_key => 'user_fk'; 

  has_many :tasks,
           :class_name  => 'Task',
	   :foreign_key => 'owner';

  validates_presence_of :email, :username, :password;
  validates_uniqueness_of :username, :email;

  def validate
     errors.add(:password, "Password should be at least 6 chars") if password.length < 6;
  end

  def self.login(login_data)
      get_user = find(:first,
                      :conditions => ["username = ? and password = ? and is_active = 1",login_data[:username],login_data[:password]]);
      return get_user ? get_user : nil;
  end

  def self.active_users
      return find(:all,
                  :conditions => ["is_active = 1"]);
  end

  def highest_priority_tasks(limit = 10)
      return tasks.find(:all,
                        :conditions => ["status_fk in (1,2)"],
                        :order => "created desc",
			:limit => limit); 
  end

  def self.get_user(user_id)
      return find(:first,
                  :conditions => ["user_id = ?",user_id]);
  end


  # stop_current_sessions
  # stop current sessions; it should be just one
  def stop_current_sessions
      # get all opened tasks for this user
      # if a task has open session, then close that session
      #open_sessions = select * from task, session where task.user_fk = _user_id_ and session.task_fk = task_id and session.end = null
      #
      #open_session = Session.find(:all,
      #                            :conditions => ["task.user_fk = ?", user_id, "session.task_fk = task_id", "session.end is null"],
      #                            :joins => ["task","session"]);
      # for open_session in open_sessions
      #     open_session.close;
      # end
  end

end
